/*
 * @lc app=leetcode.cn id=1339 lang=typescript
 *
 * [1339] 分裂二叉树的最大乘积
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxProduct(root: TreeNode | null): number {
  const dfs = (root: TreeNode | null): number => {
    if (root === null) return 0;
    let res = root.val + dfs(root.left) + dfs(root.right);
    // 找到最接近平均值的数，乘积最大
    if (Math.abs(res - avg) < Math.abs(ans - avg)) ans = res;
    return res;
  };
  let ans = 0;
  let avg = 0;
  // 第一次调用，获取累加值的数
  const total = dfs(root);
  avg = (total / 2) >> 0;
  ans = total;
  // 第二次调用，ans的值是最接近平均数的值
  dfs(root);

  return (ans * (total - ans)) % (10 ** 9 + 7);
}
// @lc code=end
